<template>
  <el-card class="search-card">
    <el-form :inline="true" class="search-form">
      <el-form-item label="通知类型">
        <el-select
            style="width: 120px"
            v-model="pageRequest.model.type"
            placeholder="请选择通知类型"
            clearable
        >
          <el-option
              v-for="(label, key) in operatorTypeMap"
              :key="key"
              :label="label"
              :value="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select
            style="width: 120px"
            v-model="pageRequest.model.status"
            placeholder="请选择状态"
            clearable>
          <el-option label="启用" :value="1"></el-option>
          <el-option label="禁用" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标题">
        <el-input
            @keyup.enter="search"
            placeholder="请输入标题"
            v-model="pageRequest.model.title"
            clearable>
        </el-input>
      </el-form-item>
<!--      <el-form-item label="内容">
        <el-input
            @keyup.enter="search"
            placeholder="请输入内容"
            v-model="pageRequest.model.content"
            clearable>
        </el-input>
      </el-form-item>-->

      <el-form-item>
        <el-button type="primary" size="default" @click="search">搜索</el-button>
        <el-button type="primary" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card class="table-card">
    <el-button icon="Plus" type="primary" plain size="default" @click="add">新增</el-button>
    <el-button icon="Delete" type="danger" plain size="default" :disabled="ids.length === 0" @click="removes">删除
    </el-button>
    <el-table @selection-change="select" border class="table" :data="items">
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column width="100px" label="ID" align="center" prop="id"></el-table-column>
      <el-table-column label="通知类型" align="center" prop="type">
        <template #default="{ row }">
          <!-- 根据 roleKey 显示对应的中文角色名称 -->
          <span>{{ operatorTypeMap[row?.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="change(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" show-overflow-tooltip></el-table-column>
      <el-table-column label="内容" align="center" prop="content" show-overflow-tooltip></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <template #="{ row }">
          <el-button type="primary" size="small" icon="Promotion" @click="openSendDrawer(row)">发送</el-button>
          <el-button type="primary" size="small" icon="Edit" @click="update(row)">编辑</el-button>
          <el-button type="primary" size="small" @click="remove(row)" icon="Delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="pageRequest.page.index"
        v-model:page-size="pageRequest.page.size"
        :page-sizes="[10, 20, 30, 50]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findPage"
        @size-change="findPage"/>
  </el-card>
  <el-drawer v-model="dialog">
    <template #header>
      <h4>{{ NoticeParams.id ? '更新通知公告' : '添加通知公告' }}</h4>
    </template>
    <template #default>
      <el-form :model="NoticeParams" :rules="rules" ref="form" label-position="right" label-width="100px">
        <el-form-item label="通知类型" prop="type">
          <el-select
              v-model="NoticeParams.type"
              placeholder="请选择通知类型"
              clearable
          >
            <el-option
                v-for="(label, key) in operatorTypeMap"
                :key="key"
                :label="label"
                :value="Number(key)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="form-item" label="状态" prop="status">
          <el-radio-group v-model="NoticeParams.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="form-item" label="标题" prop="title">
          <el-input placeholder="请输入标题" v-model="NoticeParams.title"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="内容" prop="content">
          <el-input placeholder="请输入内容" :rows="5" type="textarea" v-model="NoticeParams.content"></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="dialog = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <el-drawer v-model="drawer">
    <template #header>
      <h4>发送消息</h4>
    </template>
    <template #default>
      <el-form :model="sendForm" label-width="100px" label-position="right">
        <el-form-item label="消息标题">
          <el-input disabled v-model="sendForm.title" placeholder="请输入消息标题" />
        </el-form-item>

        <el-form-item label="消息内容">
          <el-input disabled
              v-model="sendForm.content"
              type="textarea"
              :rows="5"
              placeholder="请输入消息内容"
          />
        </el-form-item>

        <el-form-item label="接收用户">
          <el-checkbox
              style="margin-right: 30px"
              v-model="sendForm.selectAll"
              @change="handleSelectAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group
              v-model="sendForm.userIds"
              @change="handleUserSelectionChange"
          >
            <el-checkbox
                v-for="user in users"
                :key="user.id"
                :label="user.id"
                class="user-checkbox"
            >
              <span>{{ user.name }} ({{ user.username }})</span>
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="发送方式">
          <el-radio-group v-model="sendForm.sendType">
            <el-radio :label="1">立即发送</el-radio>
            <el-radio :label="2">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="sendForm.sendType === 2" label="发送时间">
          <el-date-picker
              v-model="sendForm.sendTime"
              type="datetime"
              placeholder="选择发送时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">发送</el-button>
      </div>
    </template>
  </el-drawer>

</template>

<script setup>
import {ref, onMounted, reactive, nextTick} from 'vue'
import {ElMessage} from 'element-plus'
import modal from "@/utils/modal.js"
import setting from "@/setting"
import {AddOrUpdateApi, findPageApi, removeApi, sendApi} from "@/api/system/notice/index.js";
import {findUserModelApi} from "@/api/system/user/index.js";

//控制分配角色抽屉显示与隐藏
let drawer = ref(false);

// 分页参数
const pageRequest = ref({
  page: {index: 1, size: 10},
  model: {
    type: '',
    status: '',
    title: '',
    content: '',
  }
})

// 操作人类型
const operatorTypeMap = {
  1: '公告',
  2: '私信',
  98: '跳转页面',
  99: '强弹窗通知',
}

// 基础数据
const items = ref([])
const ids = ref([])
const total = ref(0)
const dialog = ref(false)
const form = ref()

// 对象数据
const NoticeParams = reactive({
  type: '',
  status: 1,
  title: '',
  content: '',
})

// 表单校验规则
const rules = {
  type: [
    {
      required: true,
      trigger: 'change',
      message: '请选择通知类型'
    }
  ],
  status: [
    {
      required: true,
      trigger: 'change',
      message: '请选择状态'
    }
  ],
  title: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入标题'
    },
    {
      min: 2,
      max: 100,
      message: '标题长度应在2到100个字符之间',
      trigger: 'blur'
    }
  ],
  content: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入内容'
    },
    {
      min: 5,
      max: 1000,
      message: '内容长度应在5到1000个字符之间',
      trigger: 'blur'
    }
  ]
}

// 分页查询接口
const findPage = async (index = 1) => {
  pageRequest.value.page.index = index
  const result = await findPageApi(pageRequest.value)
  if (result.code === setting.SYSTEM_SUCCESS) {
    total.value = result.data.total
    items.value = result.data.items
  }
}

// 表格选择事件
const select = (value) => ids.value = value

// 添加发送消息相关的数据
const sendForm = reactive({
  title: '',
  content: '',
  selectAll: false,

  userIds: [],
  sendType: 1, // 1: 立即发送, 2: 定时发送
  sendTime: '',
  noticeId: ''
})

// 用户列表数据（示例数据，实际应从API获取）
const users = ref()

// 全选/取消全选处理
const handleSelectAllChange = (val) => {
  if (val) {
    sendForm.userIds = users.value.map(user => user.id)
  } else {
    sendForm.userIds = []
  }
}

// 用户选择变化处理
const handleUserSelectionChange = (val) => {
  sendForm.selectAll = val.length === users.value.length
}

// 确认发送
const confirmClick = async () => {
  if (!sendForm.title) {
    ElMessage.warning('请输入消息标题')
    return
  }

  if (!sendForm.content) {
    ElMessage.warning('请输入消息内容')
    return
  }

  if (sendForm.userIds.length === 0) {
    ElMessage.warning('请选择接收用户')
    return
  }

  if (sendForm.sendType === 2 && !sendForm.sendTime) {
    ElMessage.warning('请选择发送时间')
    return
  }

  try {
    // 这里调用发送消息的API
    // 将日期时间转换为时间戳（毫秒）
    sendForm.sendTime = sendForm.sendType === 2 && sendForm.sendTime
        ? new Date(sendForm.sendTime).getTime()
        : null
    const result = await sendApi(sendForm).then(item => {
      ElMessage.success('消息发送成功')
      drawer.value = false
    })

    // 重置表单
    Object.assign(sendForm, {
      title: '',
      content: '',
      selectAll: false,
      userIds: [],
      sendType: 1,
      sendTime: ''
    })
  } catch (error) {
    ElMessage.error('消息发送失败')
  }
}

// 打开发送抽屉
const openSendDrawer = (row) => {
  const userQuery = {
    status: 0
  }
  findUserModelApi(userQuery).then(result => {
    if (result.code === setting.SYSTEM_SUCCESS) {
      users.value = result.data
    }
  })
  // 将当前通知的标题和内容填充到发送表单中
  sendForm.noticeId = row.id
  sendForm.title = row.title
  sendForm.content = row.content
  drawer.value = true
}


// 搜索
const search = () => findPage()
// 重置
const reset = () => {
  pageRequest.value = {
    page: {index: 1, size: 10},
    model: {
      type: '',
      status: '',
      title: '',
      content: '',
    }
  };
  findPage();
}

// 新增操作
const add = () => {
  dialog.value = true
  Object.assign(NoticeParams, {
    id: '',
    type: 1,
    status: 1,
    title: '',
    content: '',
  })
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('type');
    form.value.clearValidate('status');
    form.value.clearValidate('title');
    form.value.clearValidate('content');
  })
}

// 更新操作
const update = (row) => {
  dialog.value = true
  Object.assign(NoticeParams, row)
  //清空上一次表单校验错误结果
  nextTick(() => {
    form.value.clearValidate('type');
    form.value.clearValidate('status');
    form.value.clearValidate('title');
    form.value.clearValidate('content');
  })
}

// 保存操作
const save = async () => {
  await form.value.validate()
  const result = await AddOrUpdateApi(NoticeParams)
  if (result.code === setting.SYSTEM_SUCCESS) {
    ElMessage.success(NoticeParams.id ? '更新成功' : '添加成功')
    dialog.value = false
    await findPage(NoticeParams.id ? pageRequest.value.page.index : 1)
  }
}

// 删除操作
const remove = async (row) => {
  await modal.confirm(`确认要删除编号为"${row.id}"的数据项吗？`)
  const result = await removeApi(row.id)
  if (result.code === setting.SYSTEM_SUCCESS) {
    ElMessage.success('删除成功')
    await findPage( items.value.length > 1 ? pageRequest.value.page.index : Math.max(1, pageRequest.value.page.index - 1))
  }
}

// 批量删除
const removes = async () => {
  const idList = ids.value.map(item => item.id).join(',')
  const result = await removeApi(idList)
  if (result.code === setting.SYSTEM_SUCCESS) {
    ElMessage.success('删除成功')
    await findPage(items.value.length > 1 ? pageRequest.value.page.index : Math.max(1, pageRequest.value.page.index - 1))
  }
}

// 状态修改
const change = async (row) => {
  try {
    const result = await AddOrUpdateApi(row)
    if (result.code === setting.SYSTEM_SUCCESS) {
      ElMessage.success('更新成功')
    }
  } catch {
    row.status = row.status === 1 ? 2 : 1
  }
}

onMounted(() => {
  findPage()
})
</script>

<style scoped>
.search-card {
  min-height: 80px;

  .search-form {
    margin-top: 15px;
  }
}

.table-card {
  margin: 10px 0;

  .table {
    margin: 10px 0;

    .form-item {
      width: 300px;
    }
  }
}

.drawer-footer {
  flex: auto;
}
</style>
